/**
 * Created by George on 2014/9/14.
 */
'use strict';

var mysql = require('../common/mysql.js');

/*
 @todo 获取用户信息
 @fields 查找字段 格式为field1，field2...
 @where  查找条件 格式为field1=? and field=?
 @values 条件值   格式为[value1，value2]
 */
exports.getUser = function*(fields, where, values) {
    var user = yield mysql.query("select " + fields + " from mh_user where " + where, values);
    if (user.length > 0) {
        return user;
    }
    return [];
};

/*
 @todo 修改用户基本信息
 @fields 修改字段 格式为field1=?，field2=?...
 @where  查找条件 格式为field1=? and field=?
 @values 条件值   格式为[value1，value2]
 */
exports.editUser = function*(fields, where, values) {
    var flag = yield mysql.query("update mh_user set " + fields + " where " + where, values);
    if (flag.affectedRows > 0) {
        return true;
    }
    return false;
};

/*
 登录时更新当前用户的tokenkey
 * @uid 需要更新的uid
 * @tokenkey 新生成的tokenkey
 * */
exports.updateToken = function*(uid, tokenkey) {
    var isSuccess = yield mysql.query("UPDATE mh_user SET tokenkey = ?, tokenttl = UNIX_TIMESTAMP() WHERE uid = ?", [tokenkey, uid]);
    if (isSuccess) {
        return true;
    } else {
        return false;
    }
};

/*
 @todo 修改用户详细信息
 @fields 修改字段 格式为field1=?，field2=?...
 @where  查找条件 格式为field1=? and field=?
 @values 条件值   格式为[value1，value2]
 */
exports.editUserDetail = function*(fields, where, values) {
    var flag = yield mysql.query("update mh_user_info set " + fields + " where " + where, values);
    if (flag != '') {
        return true;
    }
    return false;
};

/*
 * @TODO 判断自己是否已关注该用户
 * @uid 自己uid
 * @fuid 对方uid
 * */
exports.isFriend = function*(uid, fuid) {
    var isFriend = false;
    var friends = yield mysql.query('SELECT fuid FROM mh_friend WHERE uid=?', [uid]);
    if (friends.length > 0) {
        for (var i = 0; i < friends.length; i++) {
            if (friends[i].fuid == fuid) {
                isFriend = true;
                break;
            }
        }
    }

    return isFriend;
};


